package com.com.effectivejava.commonmethods.hashcode;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by User on 11/07/2014.
 */
public class HashcodeProblem{

    public static void main(String[] args) {
         Employee e1 = new Employee(1, "A");
         Employee e2 = new Employee(2, "B");
         Employee e3 = new Employee(2, "B");

        Set<Employee> employeeSet = new HashSet<Employee>();

        employeeSet.add(e1);
        employeeSet.add(e2);
        employeeSet.add(e3);

        //it prints 3, even though e2 and e3 are the same employees.
        System.out.println("employeeSet.size() = " + employeeSet.size());
   }


}

class Employee {
    private final String name;
    private final int id;

    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this)
            return true;
        if (!(obj instanceof Employee))
            return false;
        Employee e = (Employee) obj;
        return this.id == e.id;
    }
}
